package com.bawei.module_vip.ui

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bawei.lib_common.base.BaseResponse
import com.bawei.lib_common.base.BaseViewModel
import com.bawei.lib_common.base.state.Empty
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.RequestEvent
import com.bawei.lib_common.base.state.Success
import com.bawei.module_vip.data.VipItem
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class VipViewModel @Inject constructor(
    private val repository: VipRepository
) : BaseViewModel() {

    private val _requestEvent = MutableStateFlow<RequestEvent>(Empty)
    val requestEvent: StateFlow<RequestEvent> = _requestEvent

    // 存储拿到的 VIP 数据，方便后续可能的复用（也可在 Success 状态里直接带数据）
    var vipItem = MutableLiveData<VipItem>()

    fun getVipById(userId: Long) {
        _requestEvent.value = Loading
        viewModelScope.launch {
            try {
                repository.searchVipById(userId).collect { response ->
                    vipItem.value = response
                    _requestEvent.value = Success

                }
            } catch (e: Exception) {
                _requestEvent.value = Failed(e.message ?: "网络请求异常")
            }
        }
    }
}